import UserSelect from "@/components/UserSelect";
import { useUser } from "@/hooks/useUser";
import {
  Button,
  Col,
  DatePicker,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
  Tag,
} from "antd";
import { MyModalProps } from "types/modal";
import SelectUserModal from "./SelectUserModal";
import { useEffect, useState } from "react";
import { UserAddOutlined } from "@ant-design/icons";
import { addSale, getSaleDetail, updateSale } from "@/services/sale";
import dayjs from "dayjs";
import { sleep } from "@/utils";
import { useModel } from "@umijs/max";
type Props = MyModalProps & {};
const App = (props: Props) => {
  const { id, onClose = () => {}, onOk = () => {}, onEvent } = props;
  const [form] = Form.useForm();
  const [open, setOpen] = useState(false);
  const { userOptions } = useUser();
  const [loading, setLoading] = useState(false);
  const { initialState } = useModel("@@initialState");
  const [userList2, setUserList2] = useState<any[]>([]);
  const { currentUser } = initialState || {};
  const ok = async () => {
    try {
      await form.validateFields();
      const values = form.getFieldsValue();
      let { expectedSigningTime, memberList, estimatedContractAmount } = values;
      const customerList = userList2?.map((item) => {
        return {
          associationId: item.id,
          associationText: item.customerName,
        };
      });
      if (expectedSigningTime) {
        expectedSigningTime = expectedSigningTime.format("YYYY-MM-DD");
      }
      memberList = memberList?.map((item: any) => {
        return { associationId: item.value, associationText: item.label };
      });

      if (estimatedContractAmount) {
        estimatedContractAmount = estimatedContractAmount * 100;
      }
      const submitData = {
        ...values,
        expectedSigningTime,
        memberList,
        customerList,
        estimatedContractAmount,
        id,
      };
      // message.success("还未完成");
      setLoading(true);
      const { data, success } =
        id !== undefined
          ? await updateSale(submitData)
          : await addSale(submitData);
      setLoading(false);
      if (success) {
        message.success(`${id ? "编辑" : "新增"}商机成功`);
        onOk(true);
      }
    } catch (error) {
      console.log("error", error);
      setLoading(false);
    }
  };
  useEffect(() => {
    (async () => {
      if (!id) {
        return;
      }
      const { data, success, msg } = await getSaleDetail(id as any);
      if (!success) {
        message.error(msg || "获取商机详情失败");
      }
      let {
        expectedSigningTime,
        memberList,
        estimatedContractAmount,
        customerList,
        ...rest
      } = data;
      estimatedContractAmount = estimatedContractAmount / 100;
      if (expectedSigningTime) {
        expectedSigningTime = dayjs(expectedSigningTime);
      }
      memberList = memberList?.map((item: any) => {
        return {
          label: item.associationText,
          value: item.associationId,
        };
      });

      setUserList2(
        customerList?.map((item: any) => {
          return {
            id: item.associationId,
            customerName: item.associationText,
          };
        })
      );
      const defaultData = {
        ...rest,
        memberList,
        customerList,
        expectedSigningTime,
        estimatedContractAmount,
      };

      form.setFieldsValue({ ...defaultData });
    })();
  }, [id]);

  return (
    <>
      <Modal
        width={700}
        open={true}
        onOk={ok}
        onCancel={() => onClose(false)}
        title={`${id ? "编辑" : "新增"}商机`}
        okButtonProps={{
          loading,
        }}
      >
        <Form
          form={form}
          labelCol={{
            span: 5,
          }}
        >
          <Form.Item
            label="商机名称"
            name="opportunityName"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="请输入商机名称" />
          </Form.Item>
          <Form.Item
            label="负责人"
            name="projectLeaderUserId"
            initialValue={currentUser?.userid}
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Select options={userOptions} placeholder="请选择负责人" />
          </Form.Item>
          {/* 项目所在地 */}
          <Form.Item
            label="项目所在地"
            name="projectLocation"
            rules={[
              {
                required: true,
              },
            ]}
          >
            <Input placeholder="请输入项目所在地" />
          </Form.Item>

          <Row>
            <Col span={12}>
              {/* 预计签约时间 */}
              <Form.Item
                label="预计签约时间"
                name="expectedSigningTime"
                labelCol={{ span: 10 }}
              >
                <DatePicker
                  style={{ width: "100%" }}
                  placeholder="请选择预计签约时间"
                />
              </Form.Item>
            </Col>
            <Col span={12}></Col>
            <Col span={12}>
              {/* 预估合同金额 */}
              <Form.Item
                label="预估合同金额"
                name="estimatedContractAmount"
                labelCol={{ span: 10 }}
              >
                {/*  两位数 */}
                <InputNumber
                  placeholder="请输入预估合同金额"
                  addonAfter="元"
                  min={0}
                  defaultValue={0.0}
                  precision={2}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              {/* 成交概率 */}
              <Form.Item
                label="成交概率"
                name="transactionProbability"
                labelCol={{ span: 10 }}
              >
                <InputNumber
                  placeholder="请输入成交概率"
                  addonAfter="%"
                  defaultValue={0}
                  min={0}
                  max={100}
                />
              </Form.Item>
            </Col>
          </Row>
          {/* 项目相关成员 */}
          <Form.Item label="项目相关成员" name="memberList">
            <Select
              allowClear
              mode="multiple"
              maxTagCount={4}
              labelInValue
              options={userOptions}
              placeholder="请选择项目相关成员"
            />
          </Form.Item>
          {/* 客户干系人 */}
          <Form.Item
            label="客户干系人"
            name="stakeholders"
            rules={[
              {
                required: true,
                validator: (val, rules, callback) => {
                  if (userList2.length === 0) {
                    callback("请至少添加一个客户干系人");
                  } else {
                    callback();
                  }
                },
              },
            ]}
          >
            <Row gutter={[0, 10]}>
              {userList2?.map((item) => {
                return (
                  <Col key={item.id}>
                    <Tag
                      closable
                      onClose={() => {
                        const list = userList2.filter(
                          (it) => it.id !== item.id
                        );
                        setUserList2(list);
                      }}
                    >
                      <UserAddOutlined />
                      {item.customerName || "未知姓名"}
                    </Tag>
                  </Col>
                );
              })}
              <Col>
                <Button
                  size="small"
                  icon={<UserAddOutlined />}
                  onClick={() => setOpen(true)}
                >
                  添加
                </Button>
              </Col>
            </Row>
          </Form.Item>
          {/* 备注 */}
          <Form.Item label="备注" name="opportunityRemark">
            <Input.TextArea
              placeholder="请输入备注"
              rows={4}
              showCount
              maxLength={500}
            />
          </Form.Item>
        </Form>
      </Modal>
      {open ? (
        <SelectUserModal
          defaultValue={userList2}
          onOk={(user) => {
            const list = [...userList2];
            list.push(user);
            setUserList2(list);
            setOpen(false);
          }}
          onClose={() => {
            setOpen(false);
          }}
        />
      ) : null}
    </>
  );
};
export default App;
